<?php
namespace Home\Controller;

use Home\Model\PictureModel;
class UploadsController extends HomeController {
    private $folder;
    private $act;
    private $PicModel;

    public function _initialize(){
        parent::_initialize();
        $this->PicModel = new PictureModel();
    }
    public function abC(){

        echo "aaa";
    }

    public function getRand($num=6,$type=1){
        $randLength=$num;
        if ($type) {
            $chars = 'abcdefghijklmnopqrstuvwxyz';
        } else {
            $chars = '0123456789';
        }

        $len=strlen($chars);
        $randStr='';
        for ($i=0;$i<$randLength;$i++){
            $randStr.=$chars[rand(0,$len-1)];
        }
        return $randStr;
    }

    public function uploadJson(){
// 		dump($_REQUEST);

        $type = I('get.type'); // 1: 原图  2：等比原图  3：200*200图
        $fold = I('get.fold'); // 上传文件夹
        $folder = $this->get_folder($fold);
        trace('$folder = '.$folder);

        $php_path = dirname(__FILE__) . '/';
        $php_url = dirname($_SERVER['PHP_SELF']) . '/';

        //文件保存目录路径
        $save_path = $php_path . '../attached/';
        //文件保存目录URL
        $save_url = $php_url . '../attached/';

        trace($save_path);

        //文件保存目录路径
        $save_path = $_POST['uploadFilePath'] == 'attached' ? (dirname(__FILE__) . '/../attached/') : ($_SERVER['DOCUMENT_ROOT'] . $_POST['uploadFilePath'] . '/');
        //文件保存目录URL
        $save_url = $_POST['uploadFilePath'] == 'attached' ? (dirname($_SERVER['PHP_SELF']) . '/../attached/') : ($_POST['uploadFilePath'] . '/');

// 		$this->alert($_POST['uploadFilePath']);
        $save_path = $save_path.'uploads'.'/';
        $save_url  = $save_url.'uploads'.'/';

        trace($save_path);
        trace($save_url);

        if (!file_exists($save_path)){
            $this->mkdirs($save_path);
        }

        //定义允许上传的文件扩展名
        $ext_arr = array(
            'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
            'mp3' 	=> array('mp3'),
            'flash' => array('swf', 'flv'),
            'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
            'file' 	=> array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );
        //最大文件大小
        $max_size = 3145728; //1024*1024*3

        $save_path = realpath($save_path) . '/';

        //PHP上传失败
        if (!empty($_FILES['imgFile']['error'])) {
            switch($_FILES['imgFile']['error']){
                case '1':
                    $error = '超过php.ini允许的大小。';
                    break;
                case '2':
                    $error = '超过表单允许的大小。';
                    break;
                case '3':
                    $error = '图片只有部分被上传。';
                    break;
                case '4':
                    $error = '请选择图片。';
                    break;
                case '6':
                    $error = '找不到临时目录。';
                    break;
                case '7':
                    $error = '写文件到硬盘出错。';
                    break;
                case '8':
                    $error = 'File upload stopped by extension。';
                    break;
                case '999':
                default:
                    $error = '未知错误。';
            }
            $this->alert($error);
        }

        //有上传文件时
        if (empty($_FILES) === false) {
            $file_md5 = md5_file($_FILES['imgFile']['tmp_name']);
            $file_sha1 = sha1_file($_FILES['imgFile']['tmp_name']);
            $file_exist_info = $this->PicModel->chkPictures($file_md5,$file_sha1);
            if(!empty($file_exist_info)) {
                $save_url		= $file_exist_info['path'];
                $new_file_name	= $file_exist_info['url'];
                $file_id		= $file_exist_info['id'];
            } else {
                //原文件名
                $file_name = $_FILES['imgFile']['name'];
                //服务器上临时文件名
                $tmp_name = $_FILES['imgFile']['tmp_name'];
                //文件大小
                $file_size = $_FILES['imgFile']['size'];
                //检查文件名
                if (!$file_name) {
                    $this->alert("请选择文件。");
                }
                //检查目录
                if (@is_dir($save_path) === false) {
                    $this->alert("上传目录不存在。");
                }
                //检查目录写权限
                if (@is_writable($save_path) === false) {
                    $this->alert("上传目录没有写权限。");
                }
                //检查是否已上传
                if (@is_uploaded_file($tmp_name) === false) {
                    $this->alert("上传失败。");
                }
                //检查文件大小
                if ($file_size > $max_size) {
                    $this->alert("上传文件大小超过限制。");
                }
                //检查目录名
                $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
// 			trace('----------------------$dir_name = '.$dir_name);
// 			trace('----------------------2'.$ext_arr[$dir_name]);
                if (empty($ext_arr[$dir_name])) {
                    $this->alert("目录名不正确。");
                }
                //获得文件扩展名
                $temp_arr = explode(".", $file_name);
                $file_ext = array_pop($temp_arr);
                $file_ext = trim($file_ext);
                $file_ext = strtolower($file_ext);
                //检查扩展名
                if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
                    $this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
                }
                //自定义文件夹
                $dir_name .= '/'.$folder;
                //创建文件夹
                if ($dir_name !== '') {
                    $save_path .= $dir_name . "/";
                    $save_url .= $dir_name . "/";
                    if (!file_exists($save_path)) {
                        mkdir($save_path);
                    }
                }
                $ymd = date("Ymdi");
                $save_path .= $ymd . "/";
                $save_url .= $ymd . "/";
                if (!file_exists($save_path)) {
                    $this->mkdirs($save_path);
                }

                /*$ymd = date("Ymd");
                $save_path .= $dir_name . "/" . $ymd . "/";
                $save_url .= $dir_name . "/" . $ymd . "/";
                $this->mkdirs($save_path);*/

                //新文件名
                $new_file_name = date("Ymd") . '_' . rand(10000, 99999) . '.' . $file_ext;
                //移动文件
                $file_path = $save_path . $new_file_name;
                $file_path_s = $save_path.'s1_'.$new_file_name;
                $file_path_200 = $save_path.'s_200x200_'.$new_file_name;

                if (move_uploaded_file($tmp_name, $file_path) === false) {
                    $this->alert("上传文件失败。");
                } else {
                    //等比例生成缩略图
                    move_uploaded_file($this->img2thumb($file_path,$file_path_s,'','',1,0.3,$file_ext), $file_path);
                    //生成200x200缩略图
                    move_uploaded_file($this->img2thumb($file_path,$file_path_200,'200','200',1,0,$file_ext), $file_path);
                    //记录图片信息
                    $file_id = $this->PicModel->addPictures($save_url, $new_file_name, $file_md5, $file_sha1);
                }
                @chmod($file_path, 0644);
            }
// 			$file_url = $save_url . $new_file_name;
            switch ($type){
                case 1: $file_url = $save_url.$new_file_name; break;
                case 2: $file_url = $save_url.'s1_'.$new_file_name; break;
                case 3: $file_url = $save_url.'s_200x200_'.$new_file_name; break;
                default: $file_url = $save_url.'s1_'.$new_file_name;
            }
// 			$file_url = $save_url .'s_200x200_'. $new_file_name;
            trace('$file_url = '.$file_url);
            header('Content-type: text/html; charset=UTF-8');
            $data = array();
            $data['error']	 = 0;
            $data['url'] = $file_url.'?'.$file_id;
            $data['md5'] = $file_md5;
            $data['sha1'] = $file_sha1;
            $data['fileID'] = $file_id;
            $this->ajaxReturn($data);
            exit;
        }
    }

    public function fileMgrJson(){

        $fold = I('get.fold'); // 上传文件夹
        $folder = $this->get_folder($fold);
        trace('$folder = '.$folder);

        $php_path = dirname(__FILE__) . '/';
        $php_url = dirname($_SERVER['PHP_SELF']) . '/';

        //根目录路径，可以指定绝对路径，比如 /var/www/attached/
        $root_path = $php_path . '../attached/';
        //根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
        $root_url = $php_url . '../attached/';

        //文件保存目录路径
        $root_path = $_POST['uploadFilePath'] == 'attached' ? (dirname(__FILE__) . '/../attached/') : ($_SERVER['DOCUMENT_ROOT'] . $_POST['uploadFilePath'] . '/');
        //文件保存目录URL
        $root_url = $_POST['uploadFilePath'] == 'attached' ? (dirname($_SERVER['PHP_SELF']) . '/../attached/') : ($_POST['uploadFilePath'] . '/');

        $root_path = $save_path.'uploads'.'/';
        $root_url  = $save_url.'uploads'.'/';

        //图片扩展名
        $ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');

        //目录名
        $dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);
        if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
            echo "Invalid Directory name.";
            exit;
        }
        if ($dir_name !== '') {
            $root_path .= $dir_name . "/" . $folder . "/";
            $root_url .= $dir_name . "/" . $folder . "/";
            if (!file_exists($root_path)) {
                mkdir($root_path);
            }
        }
        //根据path参数，设置各路径和URL
        if (empty($_GET['path'])) {
            $current_path = realpath($root_path) . '/';
            $current_url = $root_url;
            $current_dir_path = '';
            $moveup_dir_path = '';
        } else {
            $current_path = realpath($root_path) . '/' . $_GET['path'];
            $current_url = $root_url . $_GET['path'];
            $current_dir_path = $_GET['path'];
            $moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
        }
        echo realpath($root_path);
        //排序形式，name or size or type
        $order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);

        //不允许使用..移动到上一级目录
        if (preg_match('/\.\./', $current_path)) {
            echo 'Access is not allowed.';
            exit;
        }
        //最后一个字符不是/
        if (!preg_match('/\/$/', $current_path)) {
            echo 'Parameter is not valid.';
            exit;
        }
        //目录不存在或不是目录
        if (!file_exists($current_path) || !is_dir($current_path)) {
            echo 'Directory does not exist.';
            exit;
        }

        //获取pictures模型数组
        $arrPictures = $this->PicModel->getPictureUrls();
        $arrFiles	 = array_flip($arrPictures);

        //遍历目录取得文件信息
        $file_list = array();
        if ($handle = opendir($current_path)) {
            $i = 0;
            while (false !== ($filename = readdir($handle))) {
                if ($filename{0} == '.') continue;
                // 如果是缩略图则continue
                if (substr($filename, 0, 3) == 's1_') continue;
                if (substr($filename, 0, 10) == 's_200x200_') continue;
                $file = $current_path . $filename;
                if (is_dir($file)) {
                    $file_list[$i]['is_dir'] = true; //是否文件夹
                    $file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
                    $file_list[$i]['filesize'] = 0; //文件大小
                    $file_list[$i]['is_photo'] = false; //是否图片
                    $file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
                    $file_list[$i]['filename'] = $filename;
                } else {
                    $file_list[$i]['is_dir'] = false;
                    $file_list[$i]['has_file'] = false;
                    $file_list[$i]['filesize'] = filesize($file);
                    $file_list[$i]['dir_path'] = '';
                    $file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    $file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
                    $file_list[$i]['filetype'] = $file_ext;
//					$file_list[$i]['filename'] = $filename.'?'.$arrFiles[$filename];
                    if(!empty($arrFiles[$filename])) {
                        $file_list[$i]['filename'] = $filename.'?'.$arrFiles[$filename];
                    } else {
                        $file_md5 = md5_file($file);
                        $file_sha1 = sha1_file($file);
                        $file_exist_info = $this->PicModel->chkPictures($file_md5, $file_sha1);
                        $file_list[$i]['filename'] = $filename.'?'.$file_exist_info['id'];
                    }
                }
                $file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
                $i++;
            }
            closedir($handle);
        }

        //排序
        function cmp_func($a, $b) {
            global $order;
            if ($a['is_dir'] && !$b['is_dir']) {
                return -1;
            } else if (!$a['is_dir'] && $b['is_dir']) {
                return 1;
            } else {
                if ($order == 'size') {
                    if ($a['filesize'] > $b['filesize']) {
                        return 1;
                    } else if ($a['filesize'] < $b['filesize']) {
                        return -1;
                    } else {
                        return 0;
                    }
                } else if ($order == 'type') {
                    return strcmp($a['filetype'], $b['filetype']);
                } else {
                    return strcmp($a['filename'], $b['filename']);
                }
            }
        }
        usort($file_list, 'cmp_func');

        $result = array();
        //相对于根目录的上一级目录
        $result['moveup_dir_path'] = $moveup_dir_path;
        //相对于根目录的当前目录
        $result['current_dir_path'] = $current_dir_path;
        //当前目录的URL
        $result['current_url'] = $current_url;
        //文件数
        $result['total_count'] = count($file_list);
        //文件列表数组
        $result['file_list'] = $file_list;
// 		trace($result);
        //输出JSON字符串
        header('Content-type: application/json; charset=UTF-8');

        $this->ajaxReturn($result);
// 		$json = new Services_JSON();
// 		echo $json->encode($result);
    }

    function get_folder($folder = ''){
        $token ="a";
        if(!empty($folder)) {
            return $folder;
        } else {
            if(!empty($token)){
                return $token;
            } else {
                return 'unsorted';
            }
        }
    }

    function mkdirs($dir) {
        if(!is_dir($dir)) {
            if(!$this->mkdirs(dirname($dir))){
                return false;
            }
            if(!mkdir($dir,0777)){
                return false;
            }
        }
        return true;
    }

    function create_folders($dir){
        return is_dir($dir) or (create_folders(dirname($dir)) and mkdir($dir, 0777));
    }

    public function alert($msg) {
        $data = array();
        $data['errno']	= 1;
        $data['error']	= $msg;
        $this->ajaxReturn($data);
        exit;
    }

    /**
     * 生成缩略图
     * @param string     源图绝对完整地址{带文件名及后缀名}
     * @param string     目标图绝对完整地址{带文件名及后缀名}
     * @param int        缩略图宽{0:此时目标高度不能为0，目标宽度为源图宽*(目标高度/源图高)}
     * @param int        缩略图高{0:此时目标宽度不能为0，目标高度为源图高*(目标宽度/源图宽)}
     * @param int        是否裁切{宽,高必须非0}
     * @param int/float  缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
     * @return boolean
     */
    function img2thumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0, $fileext = '')
    {
        if(!is_file($src_img))
        {
            return false;
        }
// 		$ot = $this->fileext($dst_img);
// 		$otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
        $otfunc = 'image' . ($fileext == 'jpg' ? 'jpeg' : $fileext);
        $srcinfo = getimagesize($src_img);
        $src_w = $srcinfo[0];
        $src_h = $srcinfo[1];
        $type  = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
        $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);

        $dst_h = $height;
        $dst_w = $width;
        $x = $y = 0;

        /**
         * 缩略图不超过源图尺寸（前提是宽或高只有一个）
         */
        if(($width> $src_w && $height> $src_h) || ($height> $src_h && $width == 0) || ($width> $src_w && $height == 0))
        {
            $proportion = 1;
        }
        if($width> $src_w)
        {
            $dst_w = $width = $src_w;
        }
        if($height> $src_h)
        {
            $dst_h = $height = $src_h;
        }

        if(!$width && !$height && !$proportion)
        {
            return false;
        }
        if(!$proportion)
        {
            if($cut == 0)
            {
                if($dst_w && $dst_h)
                {
                    if($dst_w/$src_w> $dst_h/$src_h)
                    {
                        $dst_w = $src_w * ($dst_h / $src_h);
                        $x = 0 - ($dst_w - $width) / 2;
                    }
                    else
                    {
                        $dst_h = $src_h * ($dst_w / $src_w);
                        $y = 0 - ($dst_h - $height) / 2;
                    }
                }
                else if($dst_w xor $dst_h)
                {
                    if($dst_w && !$dst_h)  //有宽无高
                    {
                        $propor = $dst_w / $src_w;
                        $height = $dst_h  = $src_h * $propor;
                    }
                    else if(!$dst_w && $dst_h)  //有高无宽
                    {
                        $propor = $dst_h / $src_h;
                        $width  = $dst_w = $src_w * $propor;
                    }
                }
            }
            else
            {
                if(!$dst_h)  //裁剪时无高
                {
                    $height = $dst_h = $dst_w;
                }
                if(!$dst_w)  //裁剪时无宽
                {
                    $width = $dst_w = $dst_h;
                }
                $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
                $dst_w = (int)round($src_w * $propor);
                $dst_h = (int)round($src_h * $propor);
                $x = ($width - $dst_w) / 2;
                $y = ($height - $dst_h) / 2;
            }
        }
        else
        {
            $proportion = min($proportion, 1);
            $height = $dst_h = $src_h * $proportion;
            $width  = $dst_w = $src_w * $proportion;
        }

        $src = $createfun($src_img);
        $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
        $white = imagecolorallocate($dst, 255, 255, 255);
        imagefill($dst, 0, 0, $white);

        if(function_exists('imagecopyresampled'))
        {
            imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
        }
        else
        {
            imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
        }
        $otfunc($dst, $dst_img);
        imagedestroy($dst);
        imagedestroy($src);
        return true;
    }
}